package manager.modulo.estoque.fonte;

import java.sql.SQLException;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import manager.auxiliares.*;
import manager.helpers.validation.FormatedFieldValidator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.modulo.estoque.dao.InsumoDao;
import manager.modulo.estoque.enumerator.EnumTipoInsumo;
import manager.modulo.estoque.enumerator.EnumUnidadeInsumo;
import manager.principal.fonte.JanelaLogin;

/**
 *
 * @author Thiago
 */
public class JanelaInsumo extends javax.swing.JFrame {

    int idInsumo = 0;

    /**
     * Creates new form UserWindow
     */
    public JanelaInsumo(int newIdPartner) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idInsumo = newIdPartner;
            configureWindow();
            this.setLocationRelativeTo(null);
            this.setVisible(true);

        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Materiais");
        }
    }

    private void configurarCamposObrigatorios() {
        ((TextFieldValidator) jTextField5).validarCampo();//Identificador
        ((TextFieldValidator) jTextField12).validarCampo();//Nome
        ((FormatedFieldValidator) jFormattedTextField3).validarCampo();//Valor
        ((TextFieldValidator) jTextField14).validarCampo();//Estoque Mínimo
        ((TextFieldValidator) jTextField15).validarCampo();//Estoque Máximo
        ((TextFieldValidator) jTextField16).validarCampo();//Localização        

    }

    private LinkedList<String> validarCampos() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField12).validarCampo()) {//Nome
            fieldList.add(((TextFieldValidator) jTextField12).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField5).validarCampo()) {//Identificador
            fieldList.add(((TextFieldValidator) jTextField5).getjLabel().getText());
        }
        if (!((FormatedFieldValidator) jFormattedTextField3).validarCampo()) {//Valor
            fieldList.add(((FormatedFieldValidator) jFormattedTextField3).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField14).validarCampo()) {//Estoque Minimo
            fieldList.add(((TextFieldValidator) jTextField14).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField15).validarCampo()) {//Estoque Máximo
            fieldList.add(((TextFieldValidator) jTextField15).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField16).validarCampo()) {//Localização
            fieldList.add(((TextFieldValidator) jTextField16).getjLabel().getText());
        }
        return fieldList;
    }

    private void carregarInformacoes() {
        jButton1.setText("Editar");
        jButton1.setIcon(new Icons().getEdit());

        InsumoDao insumoDao = new InsumoDao();
        insumoDao.buscar(idInsumo);

        jTextField5.setText(insumoDao.getIdentificador());//Identificador
        jTextField12.setText(insumoDao.getNome());//Nome
        jFormattedTextField3.setValue(((double) insumoDao.getValorUnitario()) / 100);
        jComboBox6.setSelectedItem(EnumUnidadeInsumo.ConvertEnumString(insumoDao.getUnidadeInsumo()));
        jTextField13.setText(Double.toString(((double) insumoDao.getQuantidade()) / 100));//Quantidade
        jTextField14.setText(Integer.toString(insumoDao.getEstoqueMinimo()));//Estoque Minimo
        jTextField15.setText(Integer.toString(insumoDao.getEstoqueMaximo()));//Estoque Maximo
        jTextField16.setText(insumoDao.getLocalizacao());//Localizacao
        jTextArea1.setText(insumoDao.getObservacao());//Observação
        jComboBox1.setSelectedItem(EnumTipoInsumo.ConvertEnumString(insumoDao.getTipoInsumo()));

    }

    private InsumoDao configurarInsumoDao(boolean editar) {
        InsumoDao insumoDao = new InsumoDao();
        if (editar) {
            insumoDao.buscar(idInsumo);
        }
        insumoDao.setIdentificador(jTextField5.getText());
        insumoDao.setNome(jTextField12.getText());
        insumoDao.setValorUnitario((int) (((Number) jFormattedTextField3.getValue()).doubleValue() * 100));
        insumoDao.setUnidadeInsumo(EnumUnidadeInsumo.ConvertStringEnum(jComboBox6.getSelectedItem().toString()));
        insumoDao.setTipoInsumo(EnumTipoInsumo.ConvertStringEnum(jComboBox1.getSelectedItem().toString()));
        insumoDao.setEstoqueMinimo(Integer.parseInt(jTextField14.getText()));
        insumoDao.setEstoqueMaximo(Integer.parseInt(jTextField15.getText()));
        insumoDao.setLocalizacao(jTextField16.getText());
        insumoDao.setObservacao(jTextArea1.getText());

        return insumoDao;
    }

    private void adicionarInsumo() {
        try {
            if (InsumoDao.getIdInsumoPorIdentificador(jTextField5.getText()) == 0 && InsumoDao.getIdInsumoPorNome(jTextField12.getText()) == 0) {
                try {
                    JanelaLogin.connection.setAutoCommit(false);

                    InsumoDao insumoDao = configurarInsumoDao(false);

                    insumoDao.inserir();

                    JanelaLogin.connection.commit();

                    JOptionPane.showMessageDialog(null, "Material inserido com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, "Inserção de Materiais");
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Este Material já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, "Inserção de Materiais");
        }
    }

    private void editarInsumo() {
        try {
            int idIdentificadorInsumo = InsumoDao.getIdInsumoPorIdentificador(jTextField5.getText());
            int idNomeMaterial = InsumoDao.getIdInsumoPorNome(jTextField12.getText());
            if ((idIdentificadorInsumo == 0 && idNomeMaterial == 0)
                    || (idIdentificadorInsumo == idInsumo && idNomeMaterial == 0)
                    || (idIdentificadorInsumo == 0 && idNomeMaterial == idInsumo)
                    || (idIdentificadorInsumo == idInsumo && idNomeMaterial == idInsumo)) {

                try {
                    JanelaLogin.connection.setAutoCommit(false);

                    InsumoDao materialDao = configurarInsumoDao(true);
                    materialDao.atualizar();

                    JanelaLogin.connection.commit();

                    JOptionPane.showMessageDialog(null, "Material atualizado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, "Atualização de Materiais");
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Este material já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configureWindow() throws SQLException {
        LinkedList<String> listaUnidade = EnumUnidadeInsumo.ListaStringUnidades();
        listaUnidade = OrdenarListas.OrdenarListaString(listaUnidade);
        for (int i = 0; i < listaUnidade.size(); i++) {
            jComboBox6.addItem(listaUnidade.get(i));
        }

        LinkedList<String> listaTipo = EnumTipoInsumo.ListaStringTipos();
        listaTipo = OrdenarListas.OrdenarListaString(listaTipo);
        for (int i = 0; i < listaTipo.size(); i++) {
            jComboBox1.addItem(listaTipo.get(i));
        }

        jComboBox1.setSelectedItem(EnumTipoInsumo.ConvertEnumString(EnumTipoInsumo.TipoInsumo.MT));

        if (idInsumo != 0) { // Edição de usuário
            carregarInformacoes();
        } else {
            this.configurarCamposObrigatorios();
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jButton6 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel18 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        jLabel35 = new javax.swing.JLabel();
        jTextField5 = new TextFieldValidator(20, 2, true, true, "text", jLabel18);
        jTextField12 = new TextFieldValidator(100, 3, true, true, "text", jLabel19);
        jComboBox6 = new javax.swing.JComboBox();
        jFormattedTextField3 = new FormatedFieldValidator(true, true, "money", jLabel20);
        jLabel44 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel22 = new javax.swing.JLabel();
        jTextField13 = new javax.swing.JTextField();
        jLabel23 = new javax.swing.JLabel();
        jTextField14 = new TextFieldValidator(10, 1, true, true, "number", jLabel23);
        jLabel24 = new javax.swing.JLabel();
        jTextField15 = new TextFieldValidator(10, 1, true, true, "number", jLabel24);
        jLabel21 = new javax.swing.JLabel();
        jTextField16 = new TextFieldValidator(40, 3, true, true, "text", jLabel21);
        jComboBox1 = new javax.swing.JComboBox();
        jLabel25 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("INSUMOS");
        setBackground(Configurations.getBackGroundColor());
        setMinimumSize(new java.awt.Dimension(550, 290));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(550, 270));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton6);
        jButton6.setBounds(130, 220, 100, 23);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(20, 220, 100, 23);

        jLabel18.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel18.setText("Identificador");
        jPanel1.add(jLabel18);
        jLabel18.setBounds(20, 20, 80, 14);

        jLabel19.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel19.setText("Nome");
        jPanel1.add(jLabel19);
        jLabel19.setBounds(140, 20, 90, 14);

        jLabel20.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel20.setText("Valor Unitário");
        jPanel1.add(jLabel20);
        jLabel20.setBounds(435, 20, 80, 14);

        jLabel35.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel35.setText("Unidade");
        jPanel1.add(jLabel35);
        jLabel35.setBounds(95, 70, 50, 14);
        jPanel1.add(jTextField5);
        jTextField5.setBounds(20, 40, 115, 20);
        jPanel1.add(jTextField12);
        jTextField12.setBounds(140, 40, 290, 20);

        jPanel1.add(jComboBox6);
        jComboBox6.setBounds(95, 90, 50, 20);
        jPanel1.add(jFormattedTextField3);
        jFormattedTextField3.setBounds(435, 40, 90, 20);

        jLabel44.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel44.setText("Observação");
        jPanel1.add(jLabel44);
        jLabel44.setBounds(20, 120, 80, 14);

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(2);
        jTextArea1.setWrapStyleWord(true);
        jScrollPane1.setViewportView(jTextArea1);
        jTextArea1.setDocument(new FixedLengthDocument(200));

        jPanel1.add(jScrollPane1);
        jScrollPane1.setBounds(20, 140, 505, 50);

        jLabel22.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel22.setText("Quantidade");
        jPanel1.add(jLabel22);
        jLabel22.setBounds(150, 70, 80, 14);

        jTextField13.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField13.setEnabled(false);
        jPanel1.add(jTextField13);
        jTextField13.setBounds(150, 90, 70, 20);

        jLabel23.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel23.setText("Mínimo");
        jPanel1.add(jLabel23);
        jLabel23.setBounds(225, 70, 50, 14);
        jPanel1.add(jTextField14);
        jTextField14.setBounds(225, 90, 70, 20);

        jLabel24.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel24.setText("Máximo");
        jPanel1.add(jLabel24);
        jLabel24.setBounds(300, 70, 50, 14);
        jPanel1.add(jTextField15);
        jTextField15.setBounds(300, 90, 70, 20);

        jLabel21.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel21.setText("Localização");
        jPanel1.add(jLabel21);
        jLabel21.setBounds(375, 70, 90, 14);
        jPanel1.add(jTextField16);
        jTextField16.setBounds(375, 90, 150, 20);

        jPanel1.add(jComboBox1);
        jComboBox1.setBounds(20, 90, 70, 20);

        jLabel25.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel25.setText("Tipo");
        jPanel1.add(jLabel25);
        jLabel25.setBounds(20, 70, 50, 14);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 550, 270);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
    }//GEN-LAST:event_formComponentResized

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LinkedList<String> fieldValidadeList = validarCampos();
        if (fieldValidadeList.size() == 0) {
            if (idInsumo == 0) {
                adicionarInsumo();
            } else {
                editarInsumo();
            }
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox6;
    private javax.swing.JFormattedTextField jFormattedTextField3;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel35;
    private javax.swing.JLabel jLabel44;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField12;
    private javax.swing.JTextField jTextField13;
    private javax.swing.JTextField jTextField14;
    private javax.swing.JTextField jTextField15;
    private javax.swing.JTextField jTextField16;
    private javax.swing.JTextField jTextField5;
    // End of variables declaration//GEN-END:variables
}
